import { Injectable } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { VerificationCode } from './mail.interface'
import * as nodemailer from 'nodemailer'

@Injectable()
export class MailService {
  private transporter: nodemailer.Transporter

  constructor(private configService: ConfigService) {
    // 从配置服务获取邮件设置
    this.transporter = nodemailer.createTransport({
      host: this.configService.get<string>('mail.host'),
      port: this.configService.get<number>('mail.port'),
      secure: this.configService.get<boolean>('mail.secure'),
      auth: {
        user: this.configService.get<string>('mail.auth.user'),
        pass: this.configService.get<string>('mail.auth.pass')
      }
      // debug: true, // 启用调试输出
      // logger: true // 启用日志
    })
  }

  // 生成验证码
  generateVerificationCode(limit = 5): VerificationCode {
    const code = Math.floor(100000 + Math.random() * 900000).toString()
    const expiresAt = Date.now() + limit * 60 * 1000

    return {
      code,
      expiresAt
    }
  }

  // 发送验证码
  async sendVerificationCode(email: string, code: string): Promise<void> {
    const mailOptions = {
      from: this.configService.get<string>('mail.from'),
      to: email,
      subject: 'BanCloud 验证码',
      html: `
        <div style="font-family: Arial, sans-serif; padding: 20px; max-width: 600px; margin: 0 auto; border: 1px solid #eee; border-radius: 5px;">
          <h2 style="color: #333;">BanCloud 验证码</h2>
          <p>您好，感谢您注册我们的服务。</p>
          <p>您的验证码是: <strong style="font-size: 18px; color: #4a90e2;">${code}</strong></p>
          <p>此验证码将在5分钟后过期。</p>
          <p style="color: #999; font-size: 12px; margin-top: 30px;">此邮件由系统自动发送，请勿回复。</p>
        </div>
      `
    }

    try {
      console.log(`正在发送验证码到 ${email}...`)
      await this.transporter.sendMail(mailOptions)
      console.log(`验证码已成功发送到 ${email}`)
    } catch (error) {
      console.error('发送邮件时出错:', error)
      throw error
    }
  }
}
